<html>
    <head>
        <title>Products</title>
        <link href="style.css" rel="stylesheet" type="text/css" media="screen" />
    </head>
    <body>
        <div id="page">
            <div id="logo">
                <h1><a href="#">Products</a></h1>
                <div class='div'>
                    &nbsp
                </div>
                <br/>
                <form onsubmit="handleSubmit(); return false;">
                    <div class='field'>
                        UPC:<input type='text' id='upc' name='upc' value='upc'>
                    </div>
                    <div class='field'>
                        Description:<input class='field' type='text' id='description' name='description'>
                    </div>
                    <div class='field'>
                        Brand:<input type='text' id='brand' name='brand'>
                    </div>
                    <div class='field'>
                        Model:<input type='text' id='model' name='model'>
                    </div>
                    <div class='field'>
                        Type:<a href='./productTypes.html'>[+]</a>
                        <span id='ptypespan' name='ptypespan'></span>
                    </div>
                    <div class='field'>
                        Quantity:<input type='button' style='width:18px;' id='delqty' onclick='AddOne("quantity",-1);' value='-' /><input type='button' id='addqty' value='+' style='width:18px;' onclick='AddOne("quantity",1);'/><input type='text' style='width:50px;' id='quantity' name='quantity'>
                    </div>
                    <div class='field'>
                        Ordered:<input type='button' style='width:18px;' id='delqty' onclick='AddOne("ordered",-1);' value='-' /><input type='button' id='addqty' value='+' style='width:18px;' onclick='AddOne("ordered",1);'/><input type='text' style='width:50px;' id='ordered' name='ordered'>
                    </div>
                    <div class='field'>
                        Cost:<input type='text' id='cost' name='cost'>
                    </div>
                    <div class='field'>
                        Price:<input type='text' id='price' name='price'>
                    </div>
                    <div class='field'>
                        <input type='button' value='Save' onclick='Save()'/>
                    </div>
                    <br/>
                    <div class='field'>
                        Search?:<input type='text' id='searcht' name='searcht'>
                    </div>
                    <div class='field'>
                        <input type='button' class='buttons' value='Search' onclick='Search(getElementById("searcht").value);'/>
                    </div>
                    <div class='field'>
                        Load?:<input type='text' id='pid' name='pid'>
                    </div>
                    <div class='field'>
                        <input type='button' value='Load' onclick='Load()'/>
                    </div>
                </form><span id="status">&nbsp;</span>
                <!-- ====================================== -->
                <!-- End HTML code.  Begin JavaScript code. -->
                <script type="text/javascript" src="../gears_init.js">
                </script>
                <script type="text/javascript" src="sample.js">
                </script>
                <script>
                    
                   
                     var query = location.search;
                     var itemid = query.substring(query.indexOf("id=") + 3, query.length);
                     
                     if (itemid != '') {
					 	
                     //var pidT = getElementById('pid');  validate browser type!!!
					 var pidT = document.all.pid; // validate browser type!!!
                     pidT.value = itemid;
					 
                     LoadXPIE();
                     }
	               /*
  else{
	                    var pidT = getElementById('pid');
	                    pidT.value = 1832;
	                    LoadX();
						}
*/
                    
                    
                    // Open this page's local database.
                    function init(){
                        var success = false;
                        
                        if (window.google && google.gears) {
                            try {
                                db = google.gears.factory.create('beta.database');
                                
                                if (db) {
                                    db.open('database-demo');
                                    db.execute('create table if not exists Product' +
                                    ' (id int primarykey,' +
                                    ' UPC text,' +
                                    ' description text,' +
                                    ' brand text,' +
                                    ' model text,' +
                                    ' type text,' +
                                    ' quantity real,' +
                                    ' ordered real,' +
                                    ' cost real,' +
                                    ' price text' +
                                    ')');
                                    
                                    success = true;
                                    // Initialize the UI at startup.
                                    
                                    displayRecentPhrases();
                                    loadProductTypes('');
                                }
                                
                            } 
                            catch (ex) {
                                setError('Could not create database: ' + ex.message);
                                alert('Could not create database: ' + ex.message);
                            }
                        }
                        
                        // Enable or disable UI elements
                        
                        var inputs = document.forms[0].elements;
                        for (var i = 0, el; el = inputs[i]; i++) {
                            el.disabled = !success;
                        }
                        
                    }
                    
                    function loadXMLDoc(dname){
                        var xmlDoc;
                        if (window.XMLHttpRequest) {
                            xmlDoc = new window.XMLHttpRequest();
                            xmlDoc.open("GET", dname, false);
                            xmlDoc.send("");
                            return xmlDoc.responseXML;
                        }
                        // IE 5 and IE 6
                        else 
                            if (ActiveXObject("Microsoft.XMLDOM")) {
                                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                                xmlDoc.async = false;
                                xmlDoc.load(dname);
                                return xmlDoc;
                            }
                        alert("Error loading document");
                        return null;
                    }
                    
                    function Save(){
                        if (!google.gears.factory || !db) {
                            return;
                        }
                        
                        var upcT = getElementById('upc');
                        var descriptionT = getElementById('description');
                        var brandT = getElementById('brand');
                        var modelT = getElementById('model');
                        var typeT = getElementById('type');
                        var quantityT = getElementById('quantity');
                        var orderedT = getElementById('ordered');
                        var costT = getElementById('cost');
                        var priceT = getElementById('price');
                        
                        var upc = upcT.value;
                        var description = descriptionT.value;
                        var brand = brandT.value;
                        var model = modelT.value;
                        var type = typeT.value;
                        var quantity = quantityT.value;
                        var ordered = orderedT.value;
                        var cost = costT.value;
                        var price = priceT.value;
                        var currTime = new Date().getTime();
                        
                        //get the new id
                        var rs = db.execute('select max(id)+1 as pid from product');
                        var newid = 0;
                        while (rs.isValidRow()) {
                            newid = rs.field(0);
                        }
                        
                        // Insert the new item.
                        // The Gears database automatically escapes/unescapes inserted values.
                        db.execute('insert into Product (id, upc, description, brand, model, type, quantity, ordered, cost, price) values (?,?,?,?,?,?,?,?,?,?)', [upc, description, brand, model, type, quantity, ordered, cost, price]);
                        alert('Product added.');
                        // Update the UI.
                        //elm.value = '';
                        //displayRecentPhrases();
                    }
                    
                    
                    function displayRecentPhrases(){
                        var recentPhrases = ['', '', ''];
                        
                        // Get the 3 most recent entries. Delete any others.
                        var rs = db.execute('select * from product order by 1 desc');
                        var index = 0;
                        while (rs.isValidRow()) {
                            if (index < 3) {
                                recentPhrases[index] = rs.field(0) + '-' + rs.field(1);
                            }
                            else {
                                alert('Nothing');//db.execute('delete from customer where Timestamp=?', [rs.field(1)]);
                            }
                            ++index;
                            rs.next();
                        }
                        rs.close();
                        
                        var status = getElementById('status');
                        status.innerHTML = '';
                        for (var i = 0; i < recentPhrases.length; ++i) {
                            var id = 'phrase' + i;
                            status.innerHTML += '<span id="' + id + '"></span><br>';
                            var bullet = '(' + (i + 1) + ') ';
                            setTextContent(getElementById(id), bullet + recentPhrases[i]);
                        }
                    }
                    
                    function Search(search){
                        var recentPhrases = ['', '', ''];
                        var query = 'select * from product where UPC like "' + search + '%"';
                        query += ' OR description like "' + search + '%"';
                        query += ' OR brand like "' + search + '%"';
                        query += ' OR model like "' + search + '%"';
                        //query += ' OR [type] like "' + search+ '%"';
                        
                        //alert(query);
                        
                        var status = getElementById('status');
                        status.innerHTML = '';//'Searching...' ;
                        var rs = db.execute(query);
                        var index = 0;
                        while (rs.isValidRow()) {
                            if (index < 3) {
                                recentPhrases[index] = rs.field(1) + '-' + rs.field(2);
                            }
                            ++index;
                            rs.next();
                        }
                        rs.close();
                        
                        
                        for (var i = 0; i < recentPhrases.length; ++i) {
                            var id = 'phrase' + i;
                            status.innerHTML += '<span id="' + id + '"></span><br>';
                            var bullet = '(' + (i + 1) + ')';
                            setTextContent(getElementById(id), bullet + recentPhrases[i]);
                        }
                    }
                    
                    function Load(){
                        var pidT = getElementById('pid');
                        var id = pidT.value;
                        
                        var rs = db.execute('select * from product where id=' + id);
                        var index = 0;
                        
                        var upcT = getElementById('upc');
                        var descriptionT = getElementById('description');
                        var brandT = getElementById('brand');
                        var modelT = getElementById('model');
                        var typeT = getElementById('type');
                        var quantityT = getElementById('quantity');
                        var orderedT = getElementById('ordered');
                        var costT = getElementById('cost');
                        var priceT = getElementById('price');
                        
                        while (rs.isValidRow()) {
                        
                            upcT.value = rs.field(1);
                            descriptionT = rs.field(2);
                            brandT.value = rs.field(3);
                            modelT.value = rs.field(4);
                            quantityT.value = rs.field(6);
                            orderedT.value = rs.field(7);
                            costT.value = rs.field(8);
                            priceT.value = rs.field(9);
                            loadProductTypes(rs.field(5));
                            
                            rs.next();
                        }
                        rs.close();
                    }
                    
                    function LoadX(){
                        var pidT = getElementById('pid');
                        var id = pidT.value;
                        
                        var upcT = getElementById('upc');
                        var descriptionT = getElementById('description');
                        var brandT = getElementById('brand');
                        var modelT = getElementById('model');
                        var typeT = getElementById('type');
                        var quantityT = getElementById('quantity');
                        var orderedT = getElementById('ordered');
                        var costT = getElementById('cost');
                        var priceT = getElementById('price');
                        
                        var xmlDoc;
                        xmlDoc = loadXMLDoc("products.xml");
                        y = xmlDoc.getElementsByTagName("products");
                        for (i = 0; i < y.length; i++) {
							x = y[i].childNodes; //a specific product
							//if(i<3)
							//alert( x[3].childNodes[0].nodeValue);
							if (x[1].childNodes[0].nodeValue == id) //check if matches an id
							{
								//alert( x[2].childNodes[0].nodeValue);
							    upcT.value = x[15].childNodes[0].nodeValue;
								descriptionT.value = x[3].childNodes[0].nodeValue;
								brandT.value = x[5].childNodes[0].nodeValue;
								modelT.value = x[7].childNodes[0].nodeValue;
								quantityT.value = x[11].childNodes[0].nodeValue;
								orderedT.value = x[13].childNodes[0].nodeValue;
								costT.value = x[17].childNodes[0].nodeValue;
								priceT.value = x[19].childNodes[0].nodeValue;
								loadProductTypes(x[9].childNodes[0].nodeValue);
								/*
 									<productid>1</productid>
								    <description>Cuenta</description>3
								    <brand>Abono</brand>5
								    <model>Cuenta</model>7
								    <typeid>ABO</typeid>9
								    <qty>0</qty>11
								    <order>0</order>13
								    <upc>Abono</upc>15
								    <cost>0</cost>17
								    <priceA>0</priceA>19
								    <priceB>0</priceB>21
								    <status>1</status>23
*/
								
								break;
							}
							else 
								document.getElementById("status").innerHTML = 'Searching...' + i;
							
						}
                        
                    }
					
					function LoadXPIE(){
                        var pidT = document.all.pid;
                        var id = pidT.value;
                        
                        var upcT = document.all.upc;
                        var descriptionT = document.all.description;
                        var brandT = document.all.brand;
                        var modelT = document.all.model;
                        var typeT = document.all.type;
                        var quantityT = document.all.quantity;
                        var orderedT = document.all.ordered;
                        var costT = document.all.cost;
                        var priceT = document.all.price;
                        alert('vars ok');
                        var xmlDoc;
                        xmlDoc = loadXMLDoc("./products.xml");
						alert('load ok');
                        y = xmlDoc.getElementsByTagName("products");
						//alert()
                        for (i = 0; i < y.length; i++) {
							x = y[i].childNodes; //a specific product
							if(i<3)
							alert( x[3].childNodes[0].nodeValue);
							if (x[1].childNodes[0].nodeValue == id) //check if matches an id
							{
								//alert( x[2].childNodes[0].nodeValue);
							    upcT.value = x[15].childNodes[0].nodeValue;
								descriptionT.value = x[3].childNodes[0].nodeValue;
								brandT.value = x[5].childNodes[0].nodeValue;
								modelT.value = x[7].childNodes[0].nodeValue;
								quantityT.value = x[11].childNodes[0].nodeValue;
								orderedT.value = x[13].childNodes[0].nodeValue;
								costT.value = x[17].childNodes[0].nodeValue;
								priceT.value = x[19].childNodes[0].nodeValue;
								loadProductTypes(x[9].childNodes[0].nodeValue);
								/*
 									<productid>1</productid>
								    <description>Cuenta</description>3
								    <brand>Abono</brand>5
								    <model>Cuenta</model>7
								    <typeid>ABO</typeid>9
								    <qty>0</qty>11
								    <order>0</order>13
								    <upc>Abono</upc>15
								    <cost>0</cost>17
								    <priceA>0</priceA>19
								    <priceB>0</priceB>21
								    <status>1</status>23
*/
								
								break;
							}
							//else 
								//document.getElementById("status").innerHTML = 'Searching...' + i;
							
						}
                        
                    }
                    
                    function loadProductTypes(sel){
                        var rs = db.execute('select * from ProductType order by 2 desc');
                        var index = 0;
                        var ptypespan = getElementById('ptypespan');
                        var itext = '';
                        itext += '<select name="producttype">';
                        while (rs.isValidRow()) {
                            itext += '<option value="' + rs.field(0) + '"';
                            if (sel == rs.field(0)) 
                                itext += ' selected ';
                            itext += '>' + rs.field(1) + '</option>';
                            rs.next();
                        }
                        rs.close();
                        itext += '</select>';
                        //alert(itext);
                        ptypespan.innerHTML = itext;
                        
                    }
                    
                    function AddOne(control, amount){
                        var pcontrol = getElementById(control);
                        var amount1 = new Number(amount);
                        var amount2 = new Number(pcontrol.value);
                        var result = amount1 + amount2;
                        
                        pcontrol.value = result;
                    }
                </script>
                </body>
            </html>
